import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/index.dart';
import 'package:common_lib/common_compoent.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_entity.dart'
    as PatientListBean;
import 'package:common_lib/repository/https.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorLoginBean;
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class PatientListBloc extends BaseBloc {
  DoctorLoginBean.DoctorUser _doctorInfo;
  var _dataSource = List<PatientListBean.Datum>();
  BehaviorSubject<List<PatientListBean.Datum>> dataSourceSubject =
      BehaviorSubject();
  BehaviorSubject<List<PatientListBean.Datum>> searchDataSourceSubject =
      BehaviorSubject();

  @override
  void dispose() {
    dataSourceSubject?.close();
    searchDataSourceSubject?.close();
  }

  @override
  void initState() async {
    super.initState();
    var doctorInfo = await UserInfoCache.getInstance().get();
    _doctorInfo = doctorInfo;
  }

  // 跳转---添加患者
  void jumpToAddPateintPage(BuildContext context) {
    Routers.navigateTo(context, CommonComponent.addPatientPage,
            parameters: Parameters()..putBool("isEdit", false))
        .then((value) {
      if (value == "refresh") {
        this.getDoctorAllPatient(() {}, () {});
      }
    });
  }

  // 跳转---编辑患者
  void jumpToEditPateintPage(BuildContext context, PatientListBean.Datum item) {
    Routers.navigateTo(context, CommonComponent.addPatientPage,
            parameters: Parameters()
              ..putBool("isEdit", true)
              ..putMap('item', item.toJson()))
        .then((value) {
      if (value == "refresh") {
        this.getDoctorAllPatient(() {}, () {});
      }
    });
  }

  // 跳转---选择患者
  void selectedPatient(context, patientInfo) {
    print('跳转---选择患者');
    EventBus.instance.post(context, CommonBusName.selectedPatient,
        Parameters()..putObj('patientInfo', patientInfo));
    Routers.pop(context);
  }

  // 网络请求---获取医生所有患者
  void getDoctorAllPatient(VoidCallback success, VoidCallback fail) async {
    var result = await CommonHttp.getDoctorAllPatient(_doctorInfo.keyID);
    if (result.isSuccess) {
      _dataSource = result.data;
      dataSourceSubject.add(_dataSource);
      success();
    } else {
      ResultBody error = result;
      ToastUtil.error(error.error.msg);
      fail();
    }
  }

  // 根据患者姓名检索
  void getSearchPatientOfName(String name) {
    var tempSearchDataSource = List<PatientListBean.Datum>();
    tempSearchDataSource = _dataSource
        .where((element) => element.patientName.contains(name))
        .toList();
    searchDataSourceSubject.add(tempSearchDataSource);
  }
}
